package com.example.permission.myjbm.utils;

import android.content.Context;

import com.example.permission.myjbm.config.Config;
import com.jbm.jbmsupplier.util.InfomationEntity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 缓存主页面内容工具
 * Created by JBMhaier on 2017/3/4.
 */
public class DataCache {
    private Context c;
    private static DataCache dataCache;
    public static DataCache getInstance(Context c){
            if(dataCache==null){
                dataCache=new DataCache(c);
            }
        return dataCache;
    };

    private DataCache(Context c){
        this.c=c;
    }
    //缓存
    public void addCache(final List<InfomationEntity> data){
        new Thread(new Runnable() {
            @Override
            public void run() {

                ObjectOutputStream out = null;
                try {
                    File file=new File(Config.CACHEPATH);
                    file.createNewFile();
                    out = new ObjectOutputStream(new FileOutputStream(file));
                    out.writeObject(data);
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        if(out!=null){
                            out.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();


    }
    //获取缓存
    public ArrayList<InfomationEntity> getCache(){
        ObjectInputStream in = null;
        ArrayList<InfomationEntity> data=null;
        try {
            in = new ObjectInputStream(new FileInputStream(Config.CACHEPATH));
         data= (ArrayList<InfomationEntity>) in.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;

    }

    //清除缓存
    public void clearCache(){
        c.getCacheDir().delete();
    }

}
